from toscawidgets.api import Widget, JSLink, CSSLink, js_function

__all__ = ["Twtools"]

# declare your static resources here

## JS dependencies can be listed at 'javascript' so they'll get included
## before
ajax_form_js = JSLink(modname=__name__, 
               filename='static/javascript/ajax_form.js', javascript=[])
json_js = JSLink(modname=__name__,
               filename='static/javascript/json2.js', javascript=[])
# my_css = CSSLink(modname=__name__, filename='static/twtools.css')

from toscawidgets.widgets.forms import TableForm
from toscawidgets.widgets.prototype import prototype_js

from formencode import Schema

class FilteringSchema(Schema):
    filter_extra_fields = True
    allow_extra_fields = True

class ActiveForm(TableForm):
    #template = """<div id="${id}">${value}</div>"""
    ## You can also define the template in a separate package and refer to it
    ## using Buffet style uris
    template = "genshi:toscawidgets.widgets.twtools.activeform.templates.table_form"

    javascript = [prototype_js, ajax_form_js, json_js]
    #css = [my_css]
    include_dynamic_js_calls = True
    

    _params = ['on_success', 'on_failure', 'clear_on_success']
    params = _params
    manager = js_function('new AjaxFormManager')

    validator = FilteringSchema
#    def __init__(self, id=None, parent=None, children=[], **kw):
#        """Initialize the widget here. The widget's initial state shall be
#        determined solely by the arguments passed to this function; two
#        widgets initialized with the same args. should behave in *exactly* the
#        same way. You should *not* rely on any external source to determine
#        initial state."""
#        super(ActiveForm, self).__init__(id, parent, children, **kw)

    def update_params(self, d):
        super(ActiveForm, self).update_params(d)
        
        if not getattr(d, 'id', None):
            raise KeyError('Ajax forms need an id')
        
        options = dict()
        for i in self._params:
            options[i] = d[i]
        
        self.add_call(self.manager(d.id, options))
